<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_giftbao/model')->方法名();
*/
namespace jy_giftbao;
defined('BY_JYA') or exit('error');
class model extends \plugin{
	public function get_active($goods_id,$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$actives=$this->get('active',array('goods_id'=>$goods_id,'stop'=>0,'start_time <'=>TIMESTAMP,'end_time >'=>TIMESTAMP));
		if(!$actives['id']){
			return false;
		}
		$lognum=pdo_count('jy_giftbao_active_log',array('active_id'=>$actives['id'],'ispay'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		if($lognum>=$actives['num'] && $actives['num']){
			return false;
		}
		$actives['title']='送礼包';
		$actives['libaos']=$actives['libaos']?json_decode($actives['libaos'],true):array();
		if(empty($actives['libaos'])){
			return false;
		}
		return $actives;
	}
	public function add_log($order,$mid=0){
		$mid=$order['mid']?:$_SESSION['uid'];
		foreach($order['goods'] as $item){
				$actives=$this->get_active($item['goodsid'],$mid);
				if($actives['id']){
					$log=array(
						'uniacid'=>$_SESSION['uniacid'],
						'mid'=>$mid,
						'active_id'=>$actives['id'],
						'goods_id'=>$item['goodsid'],
						'ordersn'=>$order['ordersn'],
						'status'=>0,
						'createtime'=>TIMESTAMP,
					);
					$this->pdo_insert('active_log',$log);
					$id=$this->pdo_insertid();
				}
		}
		return true;
	}
	public function upispay_log($order,$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$this->pdo_update('active_log',array('ispay'=>1),array('ordersn'=>$order['ordersn']));
		return true;
	}
	public function send_gift($orderid,$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$order=model('jy_weishop/order')->get_order($orderid);
		foreach($order['goods'] as $item){
				$actives=$this->get_active($item['goodsid'],$mid);
				if($actives['id']){
					$log=pdo_get('jy_giftbao_active_log',array('active_id'=>$actives['id'],'ispay'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
					if($log['libaos'] && $log['status']==0){
						$log['libaos']=json_decode($log['libaos'],true);
						foreach($log['libaos'] as $lv){
							$libao=pdo_get('jy_giftbao_libao',array('id'=>$lv['id'],'uniacid'=>$_SESSION['uniacid']));
							model('jy_weishop/libao')->add_libao($libao);
						}
					}else{
						continue;
					}
				}
		}
		return true;
	}
}
?>